<template>
  <div class="profile-page">
    <NavButtons />
    <h2>👤 个人中心</h2>

    <p>当前头像：</p>
    <img :src="avatarUrl" class="avatar-preview" />

    <p>上传新头像：</p>
    <input type="file" accept="image/*" @change="onFileChange" />

    <!-- 新增：我的游戏分数 -->
    <div class="score-board">
      <h3>🎮 我的游戏分数</h3>
      <table>
        <thead>
          <tr>
            <th>游戏</th>
            <th>分数</th>
            <th v-if="loading">加载中...</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="game in games" :key="game.key">
            <td>{{ game.name }}</td>
            <td>
              <span v-if="scores[game.key] !== null">{{ scores[game.key] }}</span>
              <span v-else>--</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <br>
    <br>
    <JspButton/>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import NavButtons from '@/components/NavButtons.vue'
import JspButton from '../components/JspButton.vue'

const userStore = useUserStore()
const defaultAvatar = new URL('backend/app/static/avatars/default.png', import.meta.url).href
const avatarUrl = computed(() => userStore.avatar || defaultAvatar)

const onFileChange = async (e) => {
  const file = e.target.files[0]
  if (!file) return
  const formData = new FormData()
  formData.append('file', file)
  try {
    const res = await fetch('http://localhost:5000/upload_avatar', {
      method: 'POST',
      credentials: 'include',
      body: formData,
    })
    const data = await res.json()
    if (data.status === 'success') {
      if (userStore.avatar === defaultAvatar) {
        userStore.setAvatar(data.data.avatar)
      } else {
        userStore.setAvatar('http://localhost:5000' + data.data.avatar)
      }
      alert('头像上传成功！')
    } else {
      alert('上传失败：' + data.message)
    }
  } catch (err) {
    console.error(err)
    alert('上传出错')
  }
}

// 游戏及接口映射
const games = [
  { key: 'eat', name: '吃豆人', api: '/get_eat_score', field: 'eat_score' },
  { key: 'snake', name: '贪吃蛇', api: '/get_snake_score', field: 'snake_score' },
  { key: 'plane', name: '飞机大战', api: '/get_plane_score', field: 'plane_score' },
  { key: 'mario', name: '超级马里奥', api: '/get_mario_score', field: 'mario_score' },
  { key: 'two', name: '2048', api: '/get_two_score', field: 'two_score' }
]

// 每个游戏分数，初始为 null
const scores = ref({
  eat: null,
  snake: null,
  plane: null,
  mario: null,
  two: null
})

const loading = ref(false)

// 获取分数
const fetchScores = async () => {
  loading.value = true
  for (const game of games) {
    try {
      const res = await fetch(`http://localhost:5000${game.api}`, {
        method: 'GET',
        credentials: 'include'
      })
      const data = await res.json()
      if (data.status === 'success') {
        scores.value[game.key] = data.data[game.field]
      } else {
        scores.value[game.key] = '--'
      }
    } catch {
      scores.value[game.key] = '--'
    }
  }
  loading.value = false
}

onMounted(() => {
  fetchScores()
})
</script>

<style scoped>
.profile-page {
  padding: 20px;
  max-width: 600px;
  margin: auto;
}

.avatar-preview {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin: 10px 0;
  object-fit: cover;
  border: 2px solid #ccc;
}

/* 新增样式 */
.score-board {
  margin-top: 30px;
  background: #181e23;
  border-radius: 14px;
  box-shadow: 0 2px 12px #0005;
  padding: 24px 20px 18px 20px;
  color: #ffd700;
}

.score-board h3 {
  font-size: 1.4em;
  margin-bottom: 15px;
  letter-spacing: 1px;
}

.score-board table {
  width: 100%;
  border-collapse: collapse;
}

.score-board th,
.score-board td {
  padding: 8px;
  text-align: center;
}

.score-board tr:nth-child(even) {
  background: #23272d;
}

.score-board th {
  background: #2e3340;
  color: #fff;
  border-radius: 4px;
}
</style>
